#!/usr/bin/env python

######################################################################
# This script checks time on servers in ${serverlist}, compares time to 
# localhost which matches ntp.org pool and alerts if any are off...
#
# Christopher D. DeVille
######################################################################

import ntplib, time, sys, smtplib, os

######################################################################
# timedif - number of seconds difference that we cannot exceed
######################################################################
timedif = 10

serverlist=['p_svr001', '192.168.1.20']

def mail(msg):
    ####################################################################################
    # mail function - to email error conditions
    ####################################################################################
    sender='%s@%s.atxg.com' % (os.environ.get('USER'), os.uname()[1])
    receiver=['user1@email.com', 'user2@email.com']
    message = """From: <%s>
To: <%s>
Subject: TIME ALERT! - Notice from host: %s 
%s
""" % (sender, receiver, os.uname()[1], msg)
    try:
   	smtpObj = smtplib.SMTP('localhost')
   	smtpObj.sendmail(sender, receiver, message)
   	print "Successfully sent email"
    except SMTPException:
   	print "Error: unable to send email"


def timequery(timeserver):
  try:
    c = ntplib.NTPClient()
    response = c.request(timeserver, version=3)
    return response.tx_time
  except: 
    mailmsg = "Time server (ntpd) not responding on host: %s!\n\r" % timeserver
    print mailmsg


def getdiff(remote, local='localhost'):
  #print timequery('pool.ntp.org')
  ### This will try to query the ntp servers and compare time, but if the values aren't right 
  ### (ie - because the ntp server is down), then this will just return 0 and we won't do a compare
  try:
    remtime = timequery(remote) 
    loctime = timequery(local)
    
    if remtime > loctime:
        diff = (remtime - loctime)
    else:
        diff = (loctime - remtime)
    return diff
  except:
    return 0 

######################################################################
# Check that our local time matches up with the remote ntp.org pool
# alert if it doesn't
######################################################################

if getdiff(remote='pool.ntp.org') > timedif:
    mailmsg='Error - time on %s is not in sync with pool.ntp.org!' % os.uname()[1]
    mail(mailmsg)
    sys.exit(mailmsg)         

errlist=[]
for i in range(len(serverlist)):
    if getdiff(remote=serverlist[i]) > timedif:
        errlist.append(serverlist[i])
 
if errlist:
    print errlist
    mailmsg='Error - Time on the following servers is NOT in sync!\n\r%s' % errlist
    mail(mailmsg)

